﻿using BasicComponents.tree;
using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace BasicComponents.dialogs
{
    /// <summary>
    /// Interaction logic for Dialog_TreeDMMC.xaml
    /// </summary>
    public partial class Dialog_CheckBoxTreeDMMC : MetroWindow
    {
        //保存元数据
        DataTable dtRAW = null;
        String dm = "";
        String mc = "";
        String fjfa;
        char spliterChar;
        String dmColName;
        String mcColName;
        Boolean isOnlyLastLevel = false;
        ObservableCollection<BasicComponents.tree.TreeModel> checkedItems = null;
        public ObservableCollection<TreeModel> CheckedItems { get => checkedItems; set => checkedItems = value; }

        public Dialog_CheckBoxTreeDMMC()
        {
            InitializeComponent();
        }
        public Dialog_CheckBoxTreeDMMC(String fjfa, char spliterChar, DataTable dt, String dmColName, String mcColName, String keywords)
        {
            InitializeComponent();
            this.dmColName = dmColName;
            this.mcColName = mcColName;
            iniData(fjfa, spliterChar, dt, dmColName, mcColName, keywords);
        }
        public Dialog_CheckBoxTreeDMMC(String fjfa, char spliterChar, DataTable dt, String dmColName, String mcColName, String keywords, Boolean isSearch)
        {
            InitializeComponent();
            this.dmColName = dmColName;
            this.mcColName = mcColName;
            iniData(fjfa, spliterChar, dt, dmColName, mcColName, keywords);
            if (isSearch)
            {
                search();
            }
        }
        public Dialog_CheckBoxTreeDMMC(String fjfa, char spliterChar, DataTable dt, String dmColName, String mcColName, String keywords, Boolean isSearch, Boolean isOnlyLastLevel)
        {
            InitializeComponent();
            this.dmColName = dmColName;
            this.mcColName = mcColName;
            this.isOnlyLastLevel = isOnlyLastLevel;
            iniData(fjfa, spliterChar, dt, dmColName, mcColName, keywords);
            if (isSearch)
            {
                search();
            }
        }
        public Dialog_CheckBoxTreeDMMC(String fjfa, char spliterChar, DataTable dt, String dmColName, String mcColName)
        {
            InitializeComponent();
            iniData(fjfa, spliterChar, dt, dmColName, mcColName);
        }
        //初始化数据
        public void iniData(String fjfa, char spliterChar, DataTable dt, String dmColName, String mcColName, String keywords)
        {
            try
            {
                this.fjfa = fjfa;
                this.spliterChar = spliterChar;
                this.dmColName = dmColName;
                this.mcColName = mcColName;
                this.dtRAW = dt;
                this.uc_keywords.TxtValue = keywords;
                if (keywords != null && !keywords.Equals(""))
                {
                    this.treeView.KeyWords = keywords;
                    this.treeView.IsShowSearchBox = true;
                }
                refresh(fjfa, spliterChar, dt, dmColName, mcColName, false);
            }
            catch (Exception e1)
            {
                MessageBox.Show("刷新数据失败，错误信息：" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        //初始化数据
        public void iniData(String fjfa, char spliterChar, DataTable dt, String dmColName, String mcColName)
        {
            try
            {
                this.fjfa = fjfa;
                this.spliterChar = spliterChar;
                this.dmColName = dmColName;
                this.mcColName = mcColName;
                this.dtRAW = dt;
                refresh(fjfa, spliterChar, dt, dmColName, mcColName, false);
            }
            catch (Exception e1)
            {
                MessageBox.Show("刷新数据失败，错误信息：" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        //刷新
        private void refresh(String fjfa, char spliterChar, DataTable dt, String dmColName, String mcColName, Boolean isExpaned)
        {
            try
            {
                String[] fjss = fjfa.Split(spliterChar);
                int[] fj = new int[fjss.Length];
                int i = 0;
                foreach (String tmp in fjss)
                {
                    fj[i] = int.Parse(tmp);
                    i++;
                }
                resetTreeData(dt, fj);
                /*
                this.treeView.Items.Clear();
                foreach (DataRow row in dt.Rows)
                {
                    String dm = row[dmColName].ToString();
                    String preDM = DMFJUtils.DMFJUtils.pearentDM(dm, spliterChar, fjfa);
                    TreeViewItem tvi_new = new TreeViewItem();
                    tvi_new.Name = "_" + row[dmColName].ToString();
                    tvi_new.Header = row[dmColName] + "-" + row[mcColName];
                    tvi_new.MouseDoubleClick += Tvi_new_MouseDoubleClick;
                    tvi_new.IsExpanded = isExpaned;
                    if (preDM == null || preDM.Trim().Equals(""))
                    {
                        this.treeView.Items.Add(tvi_new);
                    }
                    else
                    {
                        TreeViewItem preNode = null;
                        foreach (TreeViewItem tvi_root in this.treeView.Items)
                        {
                            preNode = getPreTreeNode(tvi_root, preDM);
                            if (preNode != null)
                            {
                                preNode.Items.Add(tvi_new);
                                break;
                            }
                        }
                        if (preNode == null)
                        {
                            this.treeView.Items.Add(tvi_new);
                        }
                    }
                }
                */
            }
            catch (Exception e1)
            {
                MessageBox.Show("刷新数据失败，错误信息：" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        //双击节点事件
        private void Tvi_new_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (!(sender as TreeViewItem).HasItems)
                {
                    btn_selected_Click(this.btn_selected, null);
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show("双击节点失败，错误信息：" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        //遍历节点信息
        private TreeViewItem getPreTreeNode(TreeViewItem tvi_root, String preDM)
        {
            if (tvi_root.Name.Substring(1).Equals(preDM))
            {
                return tvi_root;
            }
            else if (preDM.IndexOf(tvi_root.Name.Substring(1)) == 0 && tvi_root.HasItems)
            {
                foreach (TreeViewItem tbi in tvi_root.Items)
                {
                    TreeViewItem tvi = getPreTreeNode(tbi, preDM);
                    if (tvi != null)
                    {
                        return tvi;
                    }
                    else
                    {
                        continue;
                    }
                }
                return null;
            }
            else
            {
                return null;
            }
        }
        //搜索按钮点击事件
        private void btn_search_Click(object sender, RoutedEventArgs e)
        {
            search();
        }
        private void search()
        {

            try
            {
                String keyWorkds = this.uc_keywords.TxtValue;
                if (keyWorkds.Length <= 0)
                {
                    refresh(this.fjfa, this.spliterChar, this.dtRAW, this.dmColName, this.mcColName, false);
                    return;
                }
                // this.treeView.Items.Clear();
                DataTable dt_copy = this.dtRAW.Clone();//克隆一个表结构
                List<String> list_dm = new List<string>();//存储代码 
                                                          //第一步，过滤处节点
                foreach (DataRow row in this.dtRAW.Rows)
                {
                    ////如果包含前中括号及后括号结尾
                    //if (keyWorkds.IndexOf("[") < keyWorkds.Length && keyWorkds.EndsWith("]")) {
                    //    if(row[dmColName].ToString().)
                    //}
                    if (((row[dmColName].ToString() + "-" + row[mcColName].ToString()).IndexOf(keyWorkds) >= 0) || ((row[dmColName].ToString() + "-" + NPinyin.Pinyin.GetInitials(row[mcColName].ToString())).ToUpper().IndexOf(keyWorkds.ToUpper()) >= 0))
                    {
                        String dm = row[dmColName].ToString();
                        String preDm = DMFJUtils.DMFJUtils.pearentDM(dm, '-', this.fjfa);
                        list_dm.Add(dm);
                        if (!list_dm.Contains(preDm))
                        {
                            getPreDm(list_dm, dm, spliterChar, this.fjfa);
                        }
                    }
                }
                //第三步，添加内容至树节点中
                foreach (DataRow row in this.dtRAW.Rows)
                {
                    String dm = row[dmColName].ToString();
                    if (list_dm.Contains(dm))
                    {
                        dt_copy.ImportRow(row);
                    }
                }
                //第四步、刷新节点
                refresh(this.fjfa, spliterChar, dt_copy, dmColName, mcColName, true);
            }
            catch (Exception e1)
            {
                MessageBox.Show("筛选失败，错误信息：" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        //查找上级代码
        private void getPreDm(List<String> list_dm, String dm, Char splitChar, String fjgz)
        {
            String preDm = DMFJUtils.DMFJUtils.pearentDM(dm, splitChar, fjgz);
            if (!DMFJUtils.DMFJUtils.pearentDM(dm, splitChar, fjgz).Equals(""))
            {
                if (!list_dm.Contains(preDm))
                {
                    list_dm.Add(preDm);
                }
                getPreDm(list_dm, preDm, splitChar, fjgz);
            }
        }
        //取消筛选按钮事件
        private void btn_CancelSearch_Click(object sender, RoutedEventArgs e)
        {
            refresh(this.fjfa, this.spliterChar, this.dtRAW, this.dmColName, this.mcColName, false);
        }
        //选择按钮点击事件
        private void btn_selected_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ObservableCollection<BasicComponents.tree.TreeModel> checkedItems = BasicComponents.tree.CheckBoxTreeView.getCheckedTreeModelNode(treeView.ItemsSourceData);
                if (checkedItems == null || checkedItems.Count <= 0)
                {
                    MessageBox.Show("未选中任何信息，请选择后重试！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    try
                    {
                        this.CheckedItems = checkedItems;
                        this.Close();
                    }
                    catch (Exception e1)
                    {

                    }
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show("选择发生错误，错误：" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        //取消按钮事件
        private void btn_cancel_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckedItems = null;
                this.Close();
            }
            catch (Exception e1)
            {
                MessageBox.Show("取消失败，错误：" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void uc_keywords_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key.Equals(Key.Return) || e.Key.Equals(Key.Enter))
                {
                    btn_search_Click(sender, e);
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show("筛选失败，错误信息：" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Btn_ClearKeyWord_Click(object sender, RoutedEventArgs e)
        {
            this.uc_keywords.TxtValue = "";
        }

        //初始化树结构的内容
        private void resetTreeData(DataTable dt, int[] fj)
        {
            try
            {
                this.treeView.ItemsSourceData = new ObservableCollection<BasicComponents.tree.TreeModel>();
                if (dt != null)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        int preLen = 0;
                        String preDM = "";
                        String Xmdm = row[0].ToString();
                        String Xmmc = row[1].ToString();
                        Boolean isselected = false;
                        try
                        {
                            isselected = row[2].ToString().Trim().Equals("") ? false : true;
                        }
                        catch (Exception e1) { }
                        for (int i = 0; (i < fj.Length && preLen < Xmdm.Length); i++)
                        {
                            if ((preLen + fj[i]) >= Xmdm.Length)
                            {
                                break;
                            }
                            else
                            {
                                preLen += fj[i];
                            }
                        }
                        preDM = Xmdm.Substring(0, preLen);
                        BasicComponents.tree.TreeModel treeModel = new BasicComponents.tree.TreeModel();
                        treeModel.Header = Xmmc;
                        treeModel.Id = Xmdm;
                        if (isselected)
                        {
                            treeModel.Foreground = Brushes.Red;
                        }
                        //tvi.CheckChanged += Tvi_CheckChanged;
                        ObservableCollection<BasicComponents.tree.TreeModel> itemConllection = this.treeView.ItemsSourceData;
                        BasicComponents.tree.CheckBoxTreeView.addTreeModelToList(itemConllection, treeModel, preDM, true);
                    }
                }
                else
                {
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show("更新树结构发生错误，错误信息：" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

    }
}
